package triangle.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

/**
 * This file is part of Rodney Ryan's submission of
 * his solution to the "Triangle Puzzle".
 * <p/>
 * This class implements a ReadingStrategy that reads the
 * entire file at once. For small files.
 *
 * rodney@rodneyryan.com
 */
public class AllAtOnceReadingStrategy implements ReadingStrategy {

    private LinkedList<String> lines;

    public AllAtOnceReadingStrategy() {
        super();
        lines = new LinkedList<String>();
    }

    @Override
    public void open(File file) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            try {
                String line = bufferedReader.readLine();
                while (line != null) {
                    line = line.trim();
                    if (line.length() != 0) {
                        lines.addFirst(line);
                    }
                    line = bufferedReader.readLine();
                }

            } finally {
                bufferedReader.close();
            }

        } catch (IOException e) {
            System.out.println("Error reading file \"" + file + "\".");
            e.printStackTrace();
        }
    }

    @Override
    public String readPreviousLine() {
        if (lines.size() != 0) {
            return lines.removeFirst();
        } else {
            return null;
        }
    }

    @Override
    public void close() {
        lines.clear();
    }
}
